package org.javaparser.template.utils;

import japa.parser.ast.CompilationUnit;
import japa.parser.ast.ImportDeclaration;
import japa.parser.ast.body.ModifierSet;
import japa.parser.ast.expr.NameExpr;

import java.util.ArrayList;
import java.util.List;

import org.javaparser.template.Visibility;

public abstract class JavaParserUtils {

	public static int getModifier(int visibility) {
		if (Visibility.PUBLIC==visibility) {
			return ModifierSet.PUBLIC;
		} else if (Visibility.PROTECTED==visibility) {
			return ModifierSet.PROTECTED;
		} else if (Visibility.PRIVATE==visibility) {
			return ModifierSet.PRIVATE;
		}
		
		return ModifierSet.PRIVATE;
	}
	
	private static boolean importAlreadyPresent(
			List<ImportDeclaration> definedImports, String typeName) {
		for (ImportDeclaration importDeclaration : definedImports) {
			String importType = importDeclaration.getName().getName();
			if (importType.equals(typeName)) {
				return true;
			}
		}
		return false;
	}

	public static void addTypeInImport(CompilationUnit cu, String currentPackageName, String typeName) {
		if (!isCompleteTypeName(typeName)) {
			return;
		}

		String packageName = getPackageNameFromCompleteTypeName(typeName);
		if (!currentPackageName.equals(packageName)) {
			List<ImportDeclaration> definedImports = cu.getImports();
			if (definedImports==null) {
				definedImports = new ArrayList<ImportDeclaration>();
				cu.setImports(definedImports);
			}
			
			if (!importAlreadyPresent(definedImports, typeName)) {
				ImportDeclaration newImport = new ImportDeclaration(
							new NameExpr(typeName), false, false);
				definedImports.add(newImport);
			}
		}
	}
	
	public static boolean isCompleteTypeName(String typeName) {
		String packageName = getPackageNameFromCompleteTypeName(typeName);
		return (packageName!=null && !"".equals(packageName));
	}

	public static String getTypeNameFromCompleteTypeName(String typeName) {
		if (typeName.lastIndexOf(".")!=-1) {
			return typeName.substring(typeName.lastIndexOf(".")+1, typeName.length());
		} else {
			return typeName;
		}
	}

	public static String getPackageNameFromCompleteTypeName(String typeName) {
		if (typeName.lastIndexOf(".")!=-1) {
			return typeName.substring(0, typeName.lastIndexOf("."));
		} else {
			return null;
		}
	}

	public static String getUsedTypeName(CompilationUnit cu, String currentPackageName, String typeName) {
		String usedTypeName = typeName;
		if (isCompleteTypeName(typeName)) {
			usedTypeName = getTypeNameFromCompleteTypeName(typeName);
			addTypeInImport(cu, currentPackageName, typeName);
		}
		return usedTypeName;
	}
	
}
